package com.jm3.riscar3.alu;

import com.jm3.riscar3.core.CPU;
import com.jm3.riscar3.core.Microcontroller;
import com.jm3.riscar3.interfaces.IAR3Command;
import com.jm3.riscar3.memory.Memory;
import com.jm3.riscar3.memory.Register;

public class SUB implements IAR3Command {
	
	
	public CPU cpu;
	public Memory memory;

	public SUB(Microcontroller mcu) {
		
		this.cpu = mcu.getCPU();
		this.memory = mcu.getMemory();
		
	}

	@Override
	public void execute(String args) throws Exception {
		
		Register acc = cpu.getAcc();
		int acValue = acc.readRegister();
		int registerValue = cpu.getGRegs()[ALUUtils.getRegisterNumber(args)].readRegister();
		int complemented = ALUUtils.getTwosComplement(registerValue);
		int result = (acValue + complemented) % 256;
		
		//Set flags
		cpu.getSR().setZeroFlag(ALUUtils.isZero(result));
		cpu.getSR().setNegativeFlag(ALUUtils.isEightBitNegative(result));
		cpu.getSR().setOverflowFlag(ALUUtils.isSumOverflow(acValue, complemented, result));
		cpu.getSR().setCarryFlag(ALUUtils.isSumCarry(acValue, complemented, result));
		

	}

	@Override
	public String getOpCode() {
		// TODO Auto-generated method stub
		return "00100";
	}

}
